package com.demo.house;

import com.demo.common.constant.WebConstants;
import com.demo.common.model.House;
import com.demo.common.model.Lease;
import com.demo.common.model.User;
import com.demo.common.util.WebUtil;
import com.demo.lease.LeaseService;
import com.demo.user.UserChangePwdValidator;
import com.demo.user.UserInterceptor;
import com.demo.user.UserService;
import com.demo.user.UserValidator;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;


@Before(HouseInterceptor.class)
public class HouseController extends Controller {


    @Inject
    HouseService houseService;

    @Inject
    LeaseService leaseService;

    public void index() {
        Kv cond=Kv.create();
        if(StrKit.notBlank(getPara("housename"))){
            cond.set("housename",getPara("housename"));
        }
        if(StrKit.notBlank(getPara("houselocation"))){
            cond.set("houselocation",getPara("houselocation"));
        }
        User user=getSessionAttr("user");
        if(user.getRole().equals(WebConstants.HOUSE)){ //房东
            cond.set("userid",user.getId());
        }
        setAttr("housePage", houseService.paginate(getParaToInt(0, 1), 10,Kv.by("cond",cond)));
        render("house.html");
    }

    public void add() {
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
     * 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    @Before(HouseValidator.class)
    public void save() {
        House house=getBean(House.class);
        User user=getSessionAttr("user");
        house.setUserid(user.getId());
        house.setPublisher(user.getHm());
        //house.setLeaseing(WebConstants.NOLEASEEING);
        house.setStatus(WebConstants.NOLEASEER);
        house.save();
        redirect("/house");
    }

    public void edit() {
        setAttr("house", houseService.findById(getParaToInt()));
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
     * 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    @Before(HouseValidator.class)
    public void update() {
        getBean(House.class).update();
        redirect("/house");
    }

    public void delete() {
        houseService.deleteById(getParaToInt());
        redirect("/house");
    }

    //租户租房
    public void lease() {
        House house = houseService.findById(getParaToInt());
        house.setStatus(WebConstants.LEASEEING);
        house.update();

        User user=getSessionAttr("user");
        Lease lease = new Lease();
        lease.setHouseid(house.getId());
        lease.setHousename(house.getHousename());
        lease.setHouselocation(house.getHouselocation());
        lease.setPrice(house.getPrice());
        lease.setUserid(house.getUserid());
        lease.setStatus(WebConstants.LEASEEING);
        lease.setLeaseid(user.getId());
        lease.setPublisher(house.getPublisher());
        lease.setLeaseer(user.getHm());
        lease.save();


        redirect("/lease");
    }
}
